package com.example.mybatisplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybatisplus.common.utls.SessionUtils;
import com.example.mybatisplus.mapper.LogsMapper;
import com.example.mybatisplus.mapper.StudentsMapper;
import com.example.mybatisplus.model.domain.Logs;
import com.example.mybatisplus.model.domain.Students;
import com.example.mybatisplus.model.domain.Violations;
import com.example.mybatisplus.mapper.ViolationsMapper;
import com.example.mybatisplus.model.dto.VioDetailDto;
import com.example.mybatisplus.model.dto.VioNumberDTO;
import com.example.mybatisplus.service.StudentsService;
import com.example.mybatisplus.service.ViolationsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lxp
 * @since 2024-07-17
 */
@Service
public class ViolationsServiceImpl extends ServiceImpl<ViolationsMapper, Violations> implements ViolationsService {

    @Autowired
    private ViolationsMapper violationsMapper;

    @Autowired
    private StudentsMapper studentsMapper;


    @Autowired
    private LogsMapper logsMapper;

    @Override
    @Transactional
    public void insertAll(Violations violations) {

        violationsMapper.insertAll(violations);

    }
    @Override
    public void deleteViolation(String vioId) {
        violationsMapper.deleteById(vioId);
    }

    @Override
    public List<Violations> getAllViolations(Violations violations) {
        QueryWrapper<Violations> wrapper = new QueryWrapper<>();
        wrapper.eq("is_enabled", true);
        if(StringUtils.isNotBlank(violations.getName())){
            wrapper.like("name", violations.getName());
        }
        if(StringUtils.isNotBlank(violations.getCollege())){
            wrapper.eq("college", violations.getCollege());
        }
        if(StringUtils.isNotBlank(violations.getMajor())){
            wrapper.eq("major", violations.getMajor());
        }
        if(StringUtils.isNotBlank(violations.getGrade())){
            wrapper.eq("grade", violations.getGrade());
        }
        if(StringUtils.isNotBlank(violations.getViolationType())){
            wrapper.eq("violation_type", violations.getViolationType());
        }
        if(StringUtils.isNotBlank(violations.getResult())){
            wrapper.eq("result", violations.getResult());
        }
        if(StringUtils.isNotBlank(violations.getStudentId())){
            wrapper.like("student_id", violations.getStudentId());
        }
        if(StringUtils.isNotBlank(violations.getEnterTimeArg())){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate time = LocalDate.parse(violations.getEnterTimeArg(), formatter);
            wrapper.between("enter_time",  time, time.plusMonths(1));
        }
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<Violations> getAllViolationsNot() {
        return baseMapper.getAllRecordNot();
    }

    @Override
    public void exportUser2(HttpServletResponse response) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        QueryWrapper<Violations> wrapper = new QueryWrapper<>();
        wrapper.eq("is_enabled", false);
        List<Violations> violations = baseMapper.selectList(wrapper);
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("第一个");
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("文件号");
        cell = row.createCell(1);
        cell.setCellValue("姓名");
        cell = row.createCell(2);
        cell.setCellValue("学号");
        cell = row.createCell(3);
        cell.setCellValue("违纪详情");
        cell = row.createCell(4);
        cell.setCellValue("违纪种类");
        cell = row.createCell(5);
        cell.setCellValue("学院");
        cell = row.createCell(6);
        cell.setCellValue("专业");
        cell = row.createCell(7);
        cell.setCellValue("年级");
        cell = row.createCell(8);
        cell.setCellValue("处分结果");
        cell = row.createCell(9);
        cell.setCellValue("违纪发生时间");
        cell = row.createCell(10);
        cell.setCellValue("违纪录入时间");
        cell = row.createCell(11);
        cell.setCellValue("违纪生效时间");
        cell = row.createCell(12);
        cell.setCellValue("违纪处分时长");
        cell = row.createCell(13);
        cell.setCellValue("违纪解除时间");

        for (int i = 0; i < violations.size(); i++) {
            row = sheet.createRow(1+i);
            cell = row.createCell(0);
            cell.setCellValue(violations.get(i).getVioId());
            cell = row.createCell(1);
            cell.setCellValue(violations.get(i).getName());
            cell = row.createCell(2);
            cell.setCellValue(violations.get(i).getStudentId());
            cell = row.createCell(3);
            cell.setCellValue(violations.get(i).getViolationType());
            cell = row.createCell(4);
            cell.setCellValue(violations.get(i).getViolationCategory());
            cell = row.createCell(5);
            cell.setCellValue(violations.get(i).getCollege());
            cell = row.createCell(6);
            cell.setCellValue(violations.get(i).getMajor());
            cell = row.createCell(7);
            cell.setCellValue(violations.get(i).getGrade());
            cell = row.createCell(8);
            cell.setCellValue(violations.get(i).getResult());
            cell = row.createCell(9);
            cell.setCellValue(violations.get(i).getHappenTime().format(formatter));
            cell = row.createCell(10);
            cell.setCellValue(violations.get(i).getEnterTime().format(formatter));
            cell = row.createCell(11);
            cell.setCellValue(violations.get(i).getEffectiveTime().format(formatter));
            cell = row.createCell(12);
            cell.setCellValue(violations.get(i).getPunishmentDuration());
            cell = row.createCell(13);
            cell.setCellValue(violations.get(i).getUnremindTime().format(formatter));
        }

        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> getMajor() {
        return baseMapper.getMajor();
    }

    @Override
    public List<String> getKind() {
        return baseMapper.getKind();
    }

    @Override
    public List<String> getAcade() {
        return baseMapper.getAcade();
    }

    @Override
    public void importWhitelistSettings(MultipartFile file) {
        QueryWrapper<Students> wrapper = new QueryWrapper<>();
        Students student = new Students();
        List<Violations> violations = new ArrayList<>();
        Workbook workbook = null;
        try {
            workbook = new HSSFWorkbook(file.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Sheet sheet = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.iterator();
        if (rowIterator.hasNext()) {
            rowIterator.next();
        }

        DataFormatter dataFormatter = new DataFormatter();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Violations violations1 = new Violations();
            wrapper.eq("student_id", row.getCell(1));
            student = studentsMapper.selectByStudentId(row.getCell(1).toString());
            violations1.setVioId(dataFormatter.formatCellValue(row.getCell(0)));
            violations1.setName(student.getName());
            violations1.setStudentId(dataFormatter.formatCellValue(row.getCell(1)));
            violations1.setViolationType(dataFormatter.formatCellValue(row.getCell(2)));
            violations1.setViolationCategory(dataFormatter.formatCellValue(row.getCell(3)));
            violations1.setCollege(student.getCollege());
            violations1.setMajor(student.getMajor());
            violations1.setGrade(student.getGrade());
            violations1.setResult(dataFormatter.formatCellValue(row.getCell(4)));
            violations1.setHappenTime(LocalDateTime.parse(dataFormatter.formatCellValue(row.getCell(5)), formatter));
            violations1.setEffectiveTime(LocalDateTime.parse(dataFormatter.formatCellValue(row.getCell(6)), formatter));
            violations1.setPunishmentDuration((int)row.getCell(7).getNumericCellValue());
            violations1.setUnremindTime(violations1.getEffectiveTime().plusDays(violations1.getPunishmentDuration()));
            violations1.setEnterTime(LocalDateTime.now());
            if (violations1.getUnremindTime().isAfter(LocalDateTime.now())) {
                violations1.setIsEnabled(true);
            }else {
                violations1.setIsEnabled(false);
            }
            violationsMapper.insertAll(violations1);
            violations.add(violations1);
            Logs logs=new Logs();
            logs.setVioId(dataFormatter.formatCellValue(row.getCell(0)));
            logs.setOperationTime(LocalDateTime.now());
            logs.setOperatorAid(Long.valueOf(SessionUtils.getCurrentUser().getId()));
            logs.setOperationType("创建记录");
            logsMapper.insertAll(logs);
        }
        try {
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void exportUser(HttpServletResponse response) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        QueryWrapper<Violations> wrapper = new QueryWrapper<>();
        wrapper.eq("is_enabled", true);
        List<Violations> violations = baseMapper.selectList(wrapper);
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("第一个");
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("文件号");
        cell = row.createCell(1);
        cell.setCellValue("姓名");
        cell = row.createCell(2);
        cell.setCellValue("学号");
        cell = row.createCell(3);
        cell.setCellValue("违纪详情");
        cell = row.createCell(4);
        cell.setCellValue("违纪种类");
        cell = row.createCell(5);
        cell.setCellValue("学院");
        cell = row.createCell(6);
        cell.setCellValue("专业");
        cell = row.createCell(7);
        cell.setCellValue("年级");
        cell = row.createCell(8);
        cell.setCellValue("处分结果");
        cell = row.createCell(9);
        cell.setCellValue("违纪发生时间");
        cell = row.createCell(10);
        cell.setCellValue("违纪录入时间");
        cell = row.createCell(11);
        cell.setCellValue("违纪生效时间");
        cell = row.createCell(12);
        cell.setCellValue("违纪处分时长");
        cell = row.createCell(13);
        cell.setCellValue("违纪解除时间");

        for (int i = 0; i < violations.size(); i++) {
            row = sheet.createRow(1+i);
            cell = row.createCell(0);
            cell.setCellValue(violations.get(i).getVioId());
            cell = row.createCell(1);
            cell.setCellValue(violations.get(i).getName());
            cell = row.createCell(2);
            cell.setCellValue(violations.get(i).getStudentId());
            cell = row.createCell(3);
            cell.setCellValue(violations.get(i).getViolationType());
            cell = row.createCell(4);
            cell.setCellValue(violations.get(i).getViolationCategory());
            cell = row.createCell(5);
            cell.setCellValue(violations.get(i).getCollege());
            cell = row.createCell(6);
            cell.setCellValue(violations.get(i).getMajor());
            cell = row.createCell(7);
            cell.setCellValue(violations.get(i).getGrade());
            cell = row.createCell(8);
            cell.setCellValue(violations.get(i).getResult());
            cell = row.createCell(9);
            cell.setCellValue(violations.get(i).getHappenTime().format(formatter));
            cell = row.createCell(10);
            cell.setCellValue(violations.get(i).getEnterTime().format(formatter));
            cell = row.createCell(11);
            cell.setCellValue(violations.get(i).getEffectiveTime().format(formatter));
            cell = row.createCell(12);
            cell.setCellValue(violations.get(i).getPunishmentDuration());
            cell = row.createCell(13);
            cell.setCellValue(violations.get(i).getUnremindTime().format(formatter));
        }

        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Integer> getTypeNumber(){
        int result1Count=violationsMapper.getResult1Count();
        int result2Count=violationsMapper.getResult2Count();
        int result3Count=violationsMapper.getResult3Count();
        int result4Count=violationsMapper.getResult4Count();
        int result5Count=violationsMapper.getResult5Count();
        return Arrays.asList(result1Count, result2Count, result3Count, result4Count, result5Count);
    }

    @Override
    public List<VioNumberDTO.CollegeData> getCollegeData() {
        return violationsMapper.getCollegeData();
    }

    @Override
    public List<Integer> getTypeNumberByTimeRange(LocalDateTime startTime, LocalDateTime endTime){
        int result1Count=violationsMapper.getViolationsCountByTimeRange1(startTime, endTime);
        int result2Count=violationsMapper.getViolationsCountByTimeRange2(startTime, endTime);
        int result3Count=violationsMapper.getViolationsCountByTimeRange3(startTime, endTime);
        int result4Count=violationsMapper.getViolationsCountByTimeRange4(startTime, endTime);
        int result5Count=violationsMapper.getViolationsCountByTimeRange5(startTime, endTime);

        return Arrays.asList(result1Count, result2Count, result3Count, result4Count, result5Count);
    }

    @Override
    public List<VioNumberDTO.CollegeData> getCollegeDataByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        return violationsMapper.getCollegeDataByTimeRange(startTime, endTime);
    }
    @Override
    public void extendViolation(String vioId, String publishmentDuration){
        violationsMapper.extendViolation(vioId,Integer.parseInt(publishmentDuration));
    }

    @Override
    public List<String> getVioType(){
        return violationsMapper.getCategory();
    }
    @Override
    public List<Integer> getVioNum() {
        List<Integer> counts = new ArrayList<>();
        List<String> categories = violationsMapper.getCategory();
        for (String category : categories) {
            int count = violationsMapper.getCategoryCount(category);
            counts.add(count);
        }
        return counts;
    }
}
